#!/bin/sh
#desc: Starts sshd.
#package: openssh


# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

RSAKEY="/etc/ssh_host_rsa_key"
DSAKEY="/etc/ssh_host_dsa_key"
CERT="/etc/opendomo/keys/cacert.csr"
STCFG="/etc/opendomo/stunnel.conf"
STKEY="/etc/opendomo/keys/stunnel.pem"
# Walkaround to prevent the saveSystemConfiguration.sh error
touch /etc/ssh_host_demo
start() {
 	echo -n "Starting sshd: "
 	
	# Make sure the sshd progam exists
	[ -f /usr/sbin/sshd ] || exit 1
	
	# Check for the RSA key
	if [ ! -s $RSAKEY ] ; then
		echo -n "(generating rsa key...)"
		/usr/bin/ssh-keygen -t rsa -f $RSAKEY -N "" > /dev/null 2>&1
		chmod 0600 $RSAKEY  
		chown admin $RSAKEY
	else
		echo -n "(rsa key found!)"
	fi

	# Check for the DSA key
	if [ ! -s $DSAKEY ] ; then
		echo -n "(generating dsa key...)"
		/usr/bin/ssh-keygen -t dsa -f $DSAKEY -N "" > /dev/null 2>&1
		chmod 0600 $DSAKEY
		chown admin $DSAKEY
	else
		echo -n "(dsa key found!)"
	fi
	umask 077
	start-stop-daemon -S -q -p /var/run/sshd.pid --exec /usr/sbin/sshd -- 
	/usr/bin/logger -p notice "SSL Service started"
   
	#TODO Crear certificados para stunnel, si estos no existen
	#openssl req -new -days 365 -nodes -config stunnel.cnf -out newreq.pem -keyout stunnel.pem
	if test -f $STCFG; then
		if ! test -f $CERT; then
			openssl req -new -days 365 -nodes -config $STCFG -out $CERT \
				-keyout $STKEY 2> /dev/null >/dev/null
		fi
		if test -f $CERT; then
			stunnel $STCFG >/dev/null 2>/dev/null
		fi
	fi
	exit 0
}
stop() {
	echo -n "Stopping sshd ..."
	start-stop-daemon -K -q -p /var/run/sshd.pid
	exit 0
}
restart() {
	stop
	start
}

case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart|reload)
  	restart
	;;
  *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
esac

exit $?

